/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.common.nosql.mongodb.spring.gridfs;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;


public class GridFsClient {
	
	private GridFsTemplate gridFsTemplate;
	
//	------------------------------------------------------------------------------------------	
	public GridFSFile store(InputStream content, String filename, String contentType,DBObject metadata){
		return gridFsTemplate.store(content, filename,contentType,metadata);
	}
	
//--------------------------------------------------------------------------------------------	
	public List<GridFSDBFile> find(Query query){
		return gridFsTemplate.find(query);
	}
	public GridFSDBFile findById(String id){
		return gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
	}
	
	public List<GridFSDBFile> findByFileName(String fileName){
		return gridFsTemplate.find(new Query(Criteria.where("filename").is(fileName)));
	}
	
	public GridFSDBFile findOneByFileName(String fileName){
		return gridFsTemplate.findOne(new Query(Criteria.where("filename").is(fileName)));
	}
	
	public GridFSDBFile findByMd5(String MD5Str){
		return gridFsTemplate.findOne(new Query(Criteria.where("md5").is(MD5Str)));
	}
//--------------------------------------------------------------------------------------------------------------	
	public void delete(Query query){
		 gridFsTemplate.delete(query);
	}
	
	public void deleteById(String id){
		 gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));
	}
	
//-------------------------------------------------------------------------------------------------------------	
	public static DBObject mapToDBObject(Map<String,Object> map){
		DBObject metadata=new BasicDBObject();
		if(map!=null&&!map.isEmpty()) {
			map.forEach((key,val)->{
				metadata.put(key, val);
			});
		}
		return metadata;
	}

	public GridFsTemplate getGridFsTemplate() {
		return gridFsTemplate;
	}

	public void setGridFsTemplate(GridFsTemplate gridFsTemplate) {
		this.gridFsTemplate = gridFsTemplate;
	}

}
